package com.kstech.ks_gaz01.fragments

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.widget.RadioButton
import androidx.appcompat.app.AlertDialog
import androidx.core.view.get
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.views.DividerItemDecoration
import com.chad.library.adapter4.layoutmanager.QuickGridLayoutManager
import com.kstech.ks_gaz01.R
import com.kstech.ks_gaz01.XML_ADDRESS_MIN_MAX
import com.kstech.ks_gaz01.XML_ADDRESS_SENSOR_SUCCESS
import com.kstech.ks_gaz01.XML_ADDRESS_SETTING_BUTTON
import com.kstech.ks_gaz01.XML_SENSORSET
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.data.SensorItem
import com.kstech.ks_gaz01.databinding.FragmentSensorsettingBinding
import com.kstech.ks_gaz01.databinding.LayoutDialogSettingBinding
import com.kstech.ks_gaz01.sensorSetting.SensorSettingAdapter
import com.kstech.ks_gaz01.sensorSetting.SensorSettingMultiAdapter
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew

/**
 * author: blankii
 * created on: 2024/5/8 11:14
 * description: 标定参数界面
 */
class SensorSettingFragment :
    BaseBindingFragment<FragmentSensorsettingBinding>(FragmentSensorsettingBinding::inflate),
    SocketFragmentListener {
    private var setSuccessCount = 0
    private var clickPosition = 0
    private var radioStatus = true //选中min模式
    private lateinit var sensorAdapter: SensorSettingAdapter //左侧选择列表
    private lateinit var sensorMultiAdapter: SensorSettingMultiAdapter//右侧详情列表
    private lateinit var sensorList: ArrayList<SensorItem>
    private var setSuccessTag = false

    override fun onCreateInit() {

    }

    override fun onInitView() {
        SocketManagerNew.subscribeSocketFragmentListener(this)
        initView()
        updateView()
    }

    private fun initView() {
        /**
        check(int id)	根据 id 选中某个选项
        clearCheck()	清除所有选项的选中状态,也就时一个都没选中
        getCheckedRadioButtonId()	获取选中的选项 id
         */
        binding.apply {

            /**
             * radioGroup
             */
            radioGroup.check(radioGroup[0].id)
            radioGroup.setOnCheckedChangeListener { radioGroup, i ->
                radioStatus = !radioStatus
                /**
                 * 更新标题
                 */
                binding.titleNameView.text = getRadioButtonName()
            }
            /**
             * sensorRecyclerView
             */
            sensorRecyclerView.layoutManager = LinearLayoutManager(requireActivity())
            sensorRecyclerView.addItemDecoration(
                DividerItemDecoration(
                    requireActivity(), R.color.background_logoBar
                )
            )
            sensorAdapter = SensorSettingAdapter()
            sensorAdapter.submitList(DebugDataBean.xmlMap[XML_SENSORSET])
            sensorAdapter.setOnItemClickListener { adapter, view, position ->
                if (clickPosition == position) {
                    return@setOnItemClickListener
                }
                clickPosition = position
                updateView()
            }
            sensorRecyclerView.adapter = sensorAdapter
            /**
             * multiRecyclerView
             */
            sensorList = ArrayList()
            multiRecyclerView.layoutManager = QuickGridLayoutManager(requireActivity(), 2)
            sensorMultiAdapter = SensorSettingMultiAdapter(sensorList)
            multiRecyclerView.adapter = sensorMultiAdapter
            /**
             * 设定按钮
             */
            setting.setOnClickListener {
                showAlertDialog()
            }
        }
    }

    private fun getRadioButtonName(): String {
        if (radioStatus) {
            val radioButton = binding.radioGroup[0] as RadioButton
            return radioButton.text.toString()
        } else {
            val radioButton = binding.radioGroup[1] as RadioButton
            return radioButton.text.toString()
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun showAlertDialog() {
        val dialogBinding = LayoutDialogSettingBinding.inflate(layoutInflater)
        val dialogBuilder = AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
            .setTitle(DebugDataBean.xmlMap[XML_SENSORSET]!![clickPosition].name)
            .setMessage("请确定是否设定该参数")
        val dialog = dialogBuilder.show()
        dialogBinding.submit.setOnTouchListener { view, motionEvent ->
            when (motionEvent.action) {
                MotionEvent.ACTION_DOWN -> {
                    setSuccessCount = 0
                    setSuccessTag = false
                    /**
                     * 传感器标定模式
                     */
                    SocketManagerNew.sendWriteMsg(XML_ADDRESS_MIN_MAX, getSettingValue())
                    /**
                     * 标定
                     */
                    SocketManagerNew.sendWriteMsg(XML_ADDRESS_SETTING_BUTTON, "170")
                    /**
                     * 读取一下 读取是否标定成功
                     */
                    SocketManagerNew.addReadyLooperList(
                        true, arrayListOf(
                            SocketManagerNew.ReadBean(
                                XML_ADDRESS_SENSOR_SUCCESS
                            )
                        )
                    )

                }

                MotionEvent.ACTION_UP -> {
                    dialog.dismiss()
                    SocketManagerNew.sendWriteMsg(XML_ADDRESS_SETTING_BUTTON, "0")
                }
            }
            true
        }

    }

    private fun getDescString(position: Int): String {
        val buffer = StringBuffer()
        val msgList = DebugDataBean.xmlMap[XML_SENSORSET]!![position].msgList
        msgList!!.forEach {
            buffer.append(it + "\r\n")
        }
        return buffer.toString()
    }


    private fun getSettingValue(): String {
        val charArray = Array(16) { '0' }

        if (radioStatus) {
            charArray[2 * clickPosition] = '1'
        } else {
            charArray[2 * clickPosition + 1] = '1'
        }
        var string = ""
        charArray.forEach {
            string += it
        }
        return Integer.valueOf(string, 2).toString()
    }

    private fun updateView() {

        /**
         * 更新选中item效果
         */
        sensorAdapter.clickPosition(clickPosition)
        sensorAdapter.notifyDataSetChanged()
        /**
         * 更新max_min 模式
         * 常规min模式+max模式
         * 从gnh16车型开始  变成min和max模式+特定位置模式
         */

        val clickItem = DebugDataBean.xmlMap[XML_SENSORSET]!![clickPosition]

        /**
         * 更新其他view
         */
        val sensorSetModel = clickItem.sensorSetModel
        val radioButton0 = binding.radioGroup[0] as RadioButton
        val radioButton1 = binding.radioGroup[1] as RadioButton
        when (sensorSetModel) {
            null -> {
                radioButton0.text = "MIN模式"
                radioButton1.text = "MAX模式"
            }

            "specificPosition" -> {
                radioButton0.text = "MAX和MIN模式"
                radioButton1.text = "特定位置模式"
            }
            "specificPosition_1" -> {
                radioButton0.text = "MIN模式"
                radioButton1.text = "位置模式"
            }
        }
        /**
         * 更新标题
         */
        binding.titleNameView.text = getRadioButtonName()

        /**
         * 操作说明
         */
        binding.desc.text = getDescString(clickPosition)

        /**
         * multiRecyclerView 装载数据
         */
        sensorList.clear()
        val readParaList = clickItem.childList
        readParaList.forEach {
            //使用child 添加adapter的section
            sensorList.add(SensorItem(null, true, it.name, null, false))
            //使用item 添加adapter 的常规item
            for (item in it.itemList) {
                sensorList.add(
                    SensorItem(
                        item.para0, false, item.para1, item.revData, item.isNegativeNumber
                    )
                )
            }
        }
        sensorMultiAdapter.notifyDataSetChanged()

        /**
         * 向消息队列装载数据
         */
        sendMsg()
    }

    private fun sendMsg() {
        val itemAddressList = ArrayList<String>()
        sensorList.forEach {
            if (it.address != null) {
                itemAddressList.add(it.address)
            }
        }
        val readBeanList = ArrayList<SocketManagerNew.ReadBean>()
        itemAddressList.forEach {
            readBeanList.add(SocketManagerNew.ReadBean(it))
        }
        SocketManagerNew.addReadyLooperList(true, readBeanList)
    }


    override fun writeSuccess(address: String, value: String) {
//        showSnackBar("标定成功")
    }


    override fun readSuccess(address: String, result: ArrayList<String>) {
//        globalPrintln("展示数据,${address},result:${result[0]}")
        /**
         * XML_ADDRESS_SENSOR_SUCCESS 标定成功返回0055
         * 但是控制器标定成功需要一定时间设成0055，所以需要循环的读取
         * 0055 停留一段时间就会重新置成0，所以加了setSuccessTag
         */
        if (address == XML_ADDRESS_SENSOR_SUCCESS) {
            if (!setSuccessTag && setSuccessCount < 20 && result[0] == "0055") {
                setSuccessTag = true
                "传感器标定成功".showSnackBar()
//                SocketManagerNew.clearReadList()
                sendMsg()
            } else if (setSuccessCount >= 20 && !setSuccessTag) {
                "传感器标定失败".showSnackBar()
                sendMsg()
            } else {
                "正在请求传感器标定结果:${setSuccessCount}次".showSnackBar()
            }
            setSuccessCount++
        } else {
//            for (i in floatArray.indices) {
//                floatArray[i].revData =
//                    CalcUtil.Hex2IntStr(result[i], floatArray[i].isNegativeNumber)
//            }
            sensorList.forEach {
                if (it.address == address) {
                    it.value = result[0]
                }
            }
            sensorMultiAdapter.notifyDataSetChanged()
        }
    }

}